import axios from "axios";
import { message } from "ant-design-vue";

// 创建axios实例
const service = axios.create({
  // 根据环境变量判断是否启用mock
  baseURL:
    import.meta.env.VITE_USE_MOCK === "true"
      ? import.meta.env.VITE_MOCK_API_BASE_URL
      : import.meta.env.VITE_API_BASE_URL,
  timeout: 10000,
  headers: {
    "Content-Type": "application/json;charset=utf-8",
  },
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // 在请求发送前做一些处理，比如添加token
    const token = localStorage.getItem("token");
    if (token) {
      config.headers["Authorization"] = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    console.log(error);
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    const res = response.data;
    // 根据自定义错误码判断请求是否成功
    if (res.code === 200) {
      return res;
    } else {
      // 处理错误情况
      message.error(res.message || "请求失败");
      return Promise.reject(new Error(res.message || "请求失败"));
    }
  },
  (error) => {
    console.log("err" + error);
    // 处理 HTTP 网络错误
    let messageText = "";
    // HTTP 状态码
    const status = error.response?.status;
    switch (status) {
      case 401:
        messageText = "未授权，请重新登录";
        // 这里可以触发退出登录操作
        break;
      case 403:
        messageText = "拒绝访问";
        break;
      case 404:
        messageText = "请求错误,未找到该资源";
        break;
      case 500:
        messageText = "服务器端出错";
        break;
      default:
        messageText = "网络连接错误";
    }
    message.error(messageText);
    return Promise.reject(error);
  }
);

export function get(config, url, params) {
  return service({ ...config, url, method: "GET", params });
}

export function post(config, url, data) {
  return service({ ...config, url, method: "POST", data });
}
export function put(config, url, data) {
  return service({ ...config, url, method: "PUT", data });
}

export function del(config, url, data) {
  return service({ ...config, url, method: "DELETE", data });
}
